import { Dropdown, Popconfirm } from "antd";
import { omit } from "lodash-es";
import type { DropdownPropsType } from "./props";
import { Icon } from "@/components/Icon";
import { isFunction, isString } from "@/utils/is";

const ADropdown = Dropdown;
// const AMenu = Menu
// const AMenuItem = Menu.Item
// const AMenuDivider = Menu.Divider
const APopconfirm = Popconfirm;

export default function DropDown(props: DropdownPropsType & ComponentNode) {
	const handleClickMenu = ({ key }: { key: number }) => {
		const item = props?.dropMenuList?.[+key];
		item?.onClick?.();
	};

	const getPopConfirmAttrs = (attrs: Recordable) => {
		const originAttrs = omit(attrs, ["confirm", "cancel", "icon"]);
		if (!attrs.onConfirm && attrs.confirm && isFunction(attrs.confirm)) originAttrs.onConfirm = attrs.confirm;
		if (!attrs.onCancel && attrs.cancel && isFunction(attrs.cancel)) originAttrs.onCancel = attrs.cancel;
		return originAttrs;
	};

	// const getAttr = (key: string | number) => ({ key })

	const renderMenus = () => {
		return props.dropMenuList && props.dropMenuList.length
			? props.dropMenuList.map((item: any, index: number) => ({
					icon: item.icon && isString(item.icon) ? <Icon icon={item.icon} /> : item.icon,
					label:
						props.popconfirm && item.popConfirm ? (
							<APopconfirm {...getPopConfirmAttrs(item.popConfirm)} disabled={item.disabled}>
								{item.text}
							</APopconfirm>
						) : (
							item.text
						),
					disabled: !!item.disabled,
					key: item.key || index
			  }))
			: [];
	};

	return (
		<>
			<ADropdown
				trigger={props.trigger}
				menu={{ selectedKeys: props.selectedKeys, items: renderMenus(), onClick: handleClickMenu }}
			>
				{props.children}
			</ADropdown>
		</>
	);
}
